package com.zitangkou.gateway.config;

import com.alibaba.fastjson.JSON;
import com.zitangkou.common.enums.RespEnum;
import com.zitangkou.common.global.GlobalResp;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class MyWebFilter implements WebFilter {

    public static final String[] PATH_ARRAY = {"/api/v1/users/login/account"};

    /**
     * 鉴权排除列表
     */
    private static final List<String> PATH_LIST = Stream.of(PATH_ARRAY).collect(Collectors.toList());

    public static final String APPLICATION_JSON = "application/json";

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        String path = serverWebExchange.getRequest().getPath().toString();
        if (!PATH_LIST.contains(path) && HttpStatus.UNAUTHORIZED.equals(response.getStatusCode())) {
            // 权限不足
            String resp = JSON.toJSONString(GlobalResp.fail(RespEnum.AUTHORITY_FAIL));
            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(resp.getBytes());
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
            return response.writeWith(Mono.just(bodyDataBuffer));
        }
        return webFilterChain.filter(serverWebExchange);
    }

}
